package com.hao.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * TODO
 *
 * @author 97472
 * @version 1.0
 * @date 2021/11/29 14:56
 */
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {

        // 判断msg是否是http请求
        if (httpObject instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest) httpObject;
            String uri = httpRequest.uri();
            if (uri.contains("/favicon.ico")){
                return;
            }
            System.out.println("msg类型："+httpObject.getClass());
            System.out.println("客户端地址:"+channelHandlerContext.channel().remoteAddress());

            // 回复请求，使用http协议
            ByteBuf buf = Unpooled.copiedBuffer("hello 我是服务器", CharsetUtil.UTF_8);

            // 操作http相应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,buf);

            // 设置相应的类型
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");

            // 相应的长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());

            // 进行相应
            channelHandlerContext.writeAndFlush(response);

        }
    }

}
